--[[
	游戏服调度机器人接口
--]]

local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog = require "filelog"
local base = require "base"
local filename = "pszscheduler.lua"

local gamename = "psznode"
local router

local pszscheduler = {
    is_run = false,       --是否运行
}

local PLAYER_MAX = 10

---返回机器人的数量
function pszscheduler.getrobotnum()

end

function pszscheduler.change_schedule_state(newstate)
    pszscheduler.is_run = newstate
end

function pszscheduler.robotentermatchtable(match_type, match_level, robotnum)
    local lv = match_level
    if lv > 3 then lv = 3 end
    local min = 7500 * 10^(lv - 1)
    local max = 8500 * 10^(lv - 1)
    local moneyvalue = base.get_random(min, max)
    local robotconf = {diamond = 0, coin = 0, logicname = "psz"}
    if match_type == "diamond" then
        robotconf.diamond = moneyvalue
    elseif match_type == "coin" then
        robotconf.coin = moneyvalue
    end
    pcall(cluster.call, "robotnode", ".router", "request_robot_match", gamename, match_type, match_level, robotnum, robotconf)
end

function pszscheduler.check_alltableinfo()
    --桌子数量
    local ptable_nums = 0
	local status, result = skynet.pcall(router.get_alltableinfo)
    if status then
        if result.match_infos then
            for match_level, match_info in pairs(result.match_infos) do
                -- if match_info.game_type == 1 and match_info.base_score <= 90 then
                    -- if match_info.cur_robot_num < 1 and match_info.waiting_player <= 1 and match_info.waiting_robot == 0 then
                    --     if match_info.unfull_table_num == 0 then
                    --         pszscheduler.robotentermatchtable("diamond", match_level, 1)
                    --     end
                    -- end
                    -- filelog.debug("check_alltableinfo:", match_info.cur_total_player, match_info.cur_robot_num, match_info.waiting_robot)
                    if match_info.cur_total_player < 2 and match_info.cur_robot_num < 1 and match_info.waiting_robot == 1 then
                        pcall(pszscheduler.robotentermatchtable, "diamond", match_level, 1)
                    end
                -- end
            end
        end
    end
end

function pszscheduler.get_robot_stat()
    return pszscheduler.is_run
end

function pszscheduler.monitor()
	-- body
	skynet.fork(function()
        while true do
        	skynet.sleep(6 * 100)
            ----定时拉取游戏所有桌子信息
            if pszscheduler.is_run then
                pcall(pszscheduler.check_alltableinfo)
            end
        end
    end)
end

function pszscheduler.init(base)
    router = base
    pszscheduler.monitor()
end

-- skynet.start(function()
-- 	skynet.dispatch("lua",function(session, source, cmd, ...)
--         local f = pszscheduler[cmd]
--         if f then
--             skynet.retpack(f(...))
--         else
--             skynet.retpack()
--         end
--     end)
--     pszscheduler.monitor()
-- end)

return pszscheduler
